// 插件目前仅在小范围点对点共享，请勿传播
// 云崽插件库：https://gitee.com/yhArcadia/Yunzai-Bot-plugins-index （gitee）   https://github.com/yhArcadia/Yunzai-Bot-plugins-index  （github）
// 渔糕就读的幼稚园：134086404   爱发电https://afdian.net/a/yhArcadia 欢迎打赏~

import fetch from "node-fetch";
import { segment } from "oicq";
import plugin from "../../lib/plugins/plugin.js";
import moment from "moment";
import fs from "fs";
import os from "os";
import { promisify } from "util";
import { pipeline } from "stream";
import cfg from "../../lib/config/config.js";
const _path = process.cwd();
const path = _path + "/resources/yuhuo/picCollect";

// // 初始化文件
await initfile();

export class picCollect extends plugin {
  constructor() {
    super({
      name: "picCollect",
      dsc: "收藏图片，打标签",
      event: "message",
      priority: 100,
      rule: [
        {
          reg: "^(收藏图片|偷图)(.*)$",
          fnc: "collect",
          permission: "master",
        },
        {
          reg: "^删除图片(.*)$",
          fnc: "delete",
          permission: "master",
        },
        {
          reg: "^(检索|查找|搜索|#查看全部)图片(.*)$",
          fnc: "search",
          permission: "master",
        },
      ],
    });
  }

  //   收藏图片
  async collect(e) {
    let reply;
    if (e.source) {
      if (e.isGroup) {
        reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message;
      } else {
        reply = (await e.friend.getChatHistory(e.source.time, 1)).pop()
          ?.message;
      }
      if (reply) {
        for (let val of reply) {
          if (val.type == "image") {
            e.img = [val.url];
            break;
          }
        }
      }
    }
    if (!e.img) {
      e.reply("请对图片回复，或在此命令后带上图片");
      return false;
    }
    // 提取原始关键词
    let kWordReg = /^(收藏图片|偷图)(.*)/;
    let isSteal = kWordReg.exec(e.msg)[1];
    let rawmsg = kWordReg.exec(e.msg)[2] || "defaultTag";
    // 处理特殊字符，转换为tag-tag标准格式
    let kWord = rawmsg.trim().replace(/，|,|、| |。/g, "-");
    // logger.warn("-1", kWord);
    while (/--/.test(kWord) || /^-/.test(kWord) || /-$/.test(kWord)) {
      kWord = kWord.replace("--", "-").replace(/^-/, "").replace(/-$/, "");
    }
    // logger.warn("0", kWord);
    kWord = kWord || "defaultTag";
    // logger.warn("1", kWord);
    // return true
    // 尝试保存图片
    const response = await fetch(e.img[0]);
    // 没获取到
    if (!response.ok) {
      e.reply(["源图片下载失败，请重试"], true);
      await this.clearCD(e);
      return true;
    }
    // 默认图片类型是jpg
    let picType = "png";
    // 如果是gif就改为gif
    if (response.headers.get("content-type") == "image/gif") {
      picType = "gif";
    }

    const streamPipeline = promisify(pipeline);
    // 生成图片文件名
    let currentTime = moment(new Date()).format("YYMMDDHHmmss");
    let picPath = `${path}/pictures/${currentTime}-${kWord
      .substring(0, 200)
      .trim()}-${e.group_id || "privateAdd"}.${picType}`;
    logger.warn("【收藏图片】：", picPath);
    // 写入文件
    await streamPipeline(response.body, fs.createWriteStream(picPath));
    let tags = "\n● " + kWord.split("-").join("\n● ");
    e.reply(`成功${isSteal}，Tags为：${tags}`);
  }

  //   删除图片
  async delete(e) {
    let keyWord = e.msg.replace("删除图片", "").trim();
    if (keyWord.length == 0) {
      e.reply(`请在命令后带上关键词，以删除包含该关键词的本地图片`);
      return true;
    }
    // 读取本地文件列表
    let fileList = [];
    fs.readdirSync(path + "/pictures").forEach((fileName) =>
      fileList.push(fileName)
    );
    let count = 0;
    for (let val of fileList) {
      if (val.indexOf(keyWord) != -1) {
        let picPath = path + "/pictures/" + val;
        fs.unlink(picPath, (err) => {});
        count++;
      }
    }
    e.reply(
      `${
        count
          ? `已删除包含\n${keyWord}\n关键词的${count}张图片~`
          : `未在本地检索到包含\n${keyWord}\n关键词的图片~`
      }`
    );
    return true;
  }

  //   根据关键词检索图片
  async search(e) {
    // 取页码
    let page = 1;
    if (/第(\d+)页/.test(e.msg)) {
      page = /第(\d+)页/.exec(e.msg)[1];
      e.msg = e.msg.replace(/第(\d+)页/g, "");
    }
    page = page || 1;

    // 取关键词
    let keyWord;
    let kwords;//关键词数组
    if (e.msg == "#查看全部图片") keyWord = "";
    else {
      keyWord = e.msg.replace(/^(检索|查找|搜索)图片/, "").trim();
      // 处理特殊字符，转换为tag-tag标准格式
      kwords = keyWord.replace(/，|,|、| |。/g, "-");
      while (/--/.test(kwords) || /^-/.test(kwords) || /-$/.test(kwords)) {
        kwords = kwords.replace("--", "-").replace(/^-/, "").replace(/-$/, "");
      }
      kwords = kwords.split("-");
      3;
      logger.warn(kwords);

      if (kwords.join("").length == 0 && e.msg != "#查看全部图片") {
        e.reply(
          " 请指定要检索的关键词，或发送“#查看全部图片”以查看全部已收藏图片",
          false,
          { recallMsg: 20, at: true }
        );
        return true;
      }
    }
    // logger.warn("1--", keyWord);
    // return true
    // 读取本地文件列表
    let fileList = [];
    fs.readdirSync(path + "/pictures").forEach((fileName) => {
      fileList.push(fileName);
    });
    // 如果有筛选条件，则做进一步处理
    if (e.msg != "#查看全部图片") {
      for (let val of kwords) {
        for (let i = 0; i < fileList.length; i++) {
          if (!fileList[i].includes(val)) {fileList.splice(i, 1)
          i--};
        }
      }
    }
    // logger.warn(fileList);
    if (fileList.length == 0) {
      e.reply(
        keyWord
          ? `当前还没有收藏过包含关键词“${kwords.join("、")}”的图片`
          : "当前还没有收藏过图片"
      );
      return true;
    }

    // 页数
    let pageCount = Math.ceil(fileList.length / 50);
    if (page > pageCount) {
      e.reply(
        keyWord
          ? `包含关键词“${kwords.join("、")}”的图片共${pageCount}页哦`
          : `已收藏的图片共${pageCount}页哦`
      );
      return true;
    }
    // 取一页
    let onePage = fileList.slice((page - 1) * 50, page * 50);
    // 构造合并消息
    var data_msg = [];
    if (pageCount > 1)
      // 写入简述检索结果
      data_msg.push({
        message: `${
          keyWord ? `检索到包含关键词“${kwords.join("、")}”的` : "已收藏"
        }图片共${
          fileList.length
        }张、${pageCount}页，当前为第${page}页。您可发送“${
          keyWord
            ? `检索图片${kwords.join("、")}第1页，检索图片${keyWord}第2页……`
            : "#查看全部图片第1页，#查看全部图片第2页……"
        }”来查看对应页面`,
        nickname: Bot.nickname,
        user_id: cfg.qq,
      });
    else
      data_msg.push({
        message: keyWord
          ? `检索到包含关键词“${kwords.join("、")}”的图片：共${fileList.length}张`
          : `检索到已收藏图片：共${fileList.length}张`,
        nickname: Bot.nickname,
        user_id: cfg.qq,
      });

    //   return true
    //   将图片push进合并消息
    for (let val of onePage) {
      let summarys = val.split("-");
      summarys.splice(summarys.length - 1, 1);
      let tags = summarys.slice(1);
      // logger.warn(summarys);
      // return true

      let picPath = path + "/pictures/" + val;
      // logger.info(picPath)
      let bitMap = fs.readFileSync(picPath);
      let base64 = Buffer.from(bitMap, "binary").toString("base64");
      data_msg.push({
        message: [
          `id：${summarys[0]}`,
          segment.image(`base64://${base64}`),
          // `Tags:\n● ${tags.join("\n● ")}`,
          `● ${tags.join("\n● ")}`,
        ],
        nickname: Bot.nickname,
        user_id: cfg.qq,
      });
    }

    let sendRes = null;
    if (e.isGroup)
      sendRes = await e.reply(await e.group.makeForwardMsg(data_msg));
    else sendRes = await e.reply(await e.friend.makeForwardMsg(data_msg));

    if (!sendRes) {
      e.reply(
        "遇到风控，消息发送失败，改为纯文字发送。您可排查定位其中导致风控的图片，将其删除。"
      );
      data_msg = data_msg.slice(0, 1);

      for (let val of onePage) {
        let summarys = val.split("-");
        summarys.splice(summarys.length - 1, 1);
        let tags = summarys.slice(1);
        data_msg.push({
          message: [
            `time：${summarys[0]}\n`,
            "[图片]\n",
            // `Tags:\n● ${tags.join("\n● ")}`,
            `● ${tags.join("\n● ")}`,
          ],
        });
      }
      let sendRes = null;
      if (e.isGroup)
        sendRes = await e.reply(await e.group.makeForwardMsg(data_msg));
      else sendRes = await e.reply(await e.friend.makeForwardMsg(data_msg));
      if (!sendRes) {
        e.reply("消息发送失败，去看看有没有可能导致风控的文件名吧");
      }
    }
    return true;
  }
}

// 初始化文件=====================
async function initfile() {
  initPath(path + "/pictures");
}

// 初始化路径 =======================
async function initPath(thisPath) {
  if (fs.existsSync(thisPath)) return true;
  // 取上一级路径
  let symbol = "/";
  if (os.platform() == "win32") symbol = "/";
  let upperPath = thisPath.split(symbol);
  upperPath.splice(-1);
  upperPath = upperPath.join(symbol);
  // 如果不存在上一级路径则递归处理
  if (!fs.existsSync(upperPath)) await initPath(upperPath);
  // 创建本级路径
  fs.mkdirSync(thisPath);
}
